$(function () {
    // jQuery methods go here...

    const csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    $.ajaxSetup({
        beforeSend: function (xhr, settings) {
            // if not safe method, set csrftoken
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });


    // $("#email").on("input", function () {
    //     // https://emailregex.com/
    //     const emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    //     const email = $(this).val();
    //     if (emailRegex.test(email)) {
    //         const data = new FormData();
    //         data.append('email', email);
    //         $.ajax({
    //             url: "/eamil/verify/",
    //             method: 'post',
    //             data,
    //             processData: false,
    //             contentType: false,
    //             success: function (res, status) {
    //                 $(this).addClass("is_valid");
    //             },
    //             error: function (res) {
                    
    //             }
    //         });
    //     }
    // });

    $("#captcha-button").click(function () {
        $(this).attr({ "disabled": true });
        let timer = 60; // wait for 60s
        let timerId = setInterval(() => {
            timer -= 1;
            $(this).text(`${timer}s后重试`);
            if (timer === 0) {
                clearInterval(timerId);
                timer = 60;
                $(this).attr({ "disabled": false });
                $(this).text("获取验证码");
            }
        }, 1000);


        // For more about post data,
        // see: https://stackoverflow.com/a/8244082/15172980

        const email = $("#email").val();
        const data = new FormData();
        data.append('email', email);
        $.ajax({
            url: "/captcha/",
            method: 'post',
            data,
            processData: false,
            contentType: false,
            success: function (res, status) {
                alert("验证码发送成功！");
            },
            error: function (res) {
                alert("验证码发送失败！");
            }
        });
    });
});